package com.yupi.project.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.service.InterfaceInfoService;
import com.yupi.project.service.InterfaceInvokeInfoService;
import com.yupi.project.service.UserService;
import com.yupi.yuapicommon.model.common.*;
import com.yupi.yuapicommon.model.constant.CommonConstant;
import com.yupi.yuapicommon.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.yupi.yuapicommon.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.yupi.yuapicommon.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.yupi.yuapicommon.model.dto.interfaceinfo.InvokeRequest;
import com.yupi.yuapicommon.model.entity.InterfaceInfo;
import com.yupi.yuapicommon.model.entity.InterfaceInvokeInfo;
import com.yupi.yuapicommon.model.entity.User;
import com.yupi.yuapicommon.model.vo.InterfaceInfoVo;
import com.zzsource.yuapicliensdk.model.response.ResultResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.yupi.yuapicommon.model.enums.InterfaceInfoStatusEnum.OFFLINE;
import static com.yupi.yuapicommon.model.enums.InterfaceInfoStatusEnum.ONLINE;

/**
 * @description: 接口信息
 * @author SummerBird
 * @date 2024/2/19 10:27
 * @version 1.0
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private InterfaceInvokeInfoService interfaceInvokeInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("添加接口(admin)")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        interfaceInfo.setHeaderParams(JSON.toJSONString(interfaceInfoAddRequest.getHeaderParams()));
        interfaceInfo.setQueryParams(JSON.toJSONString(interfaceInfoAddRequest.getQueryParams()));
        interfaceInfo.setBodyParams(JSON.toJSONString(interfaceInfoAddRequest.getBodyParams()));
        interfaceInfo.setCreateTime(String.valueOf(new Timestamp(System.currentTimeMillis())));
        interfaceInfo.setUpdateTime(String.valueOf(new Timestamp(System.currentTimeMillis())));
        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());

        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("删除接口(admin)")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("更新接口(admin)")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                            HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        interfaceInfo.setHeaderParams(JSON.toJSONString(interfaceInfoUpdateRequest.getHeaderParams()));
        interfaceInfo.setQueryParams(JSON.toJSONString(interfaceInfoUpdateRequest.getQueryParams()));
        interfaceInfo.setBodyParams(JSON.toJSONString(interfaceInfoUpdateRequest.getBodyParams()));
        interfaceInfo.setUpdateTime(String.valueOf(new Timestamp(System.currentTimeMillis())));
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取接口")
    public BaseResponse<InterfaceInfoVo> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
        BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
        interfaceInfoVo.setBodyParams(JSON.parseArray(interfaceInfo.getBodyParams(), InvokeRequest.Field.class));
        interfaceInfoVo.setQueryParams(JSON.parseArray(interfaceInfo.getQueryParams(), InvokeRequest.Field.class));
        interfaceInfoVo.setHeaderParams(JSON.parseArray(interfaceInfo.getHeaderParams(), InvokeRequest.Field.class));
        return ResultUtils.success(interfaceInfoVo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    @ApiOperation("获取列表(admin)")
    public BaseResponse<List<InterfaceInfoVo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        List<InterfaceInfoVo> interfaceInfoVoList = interfaceInfoList.stream().map(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
            interfaceInfoVo.setQueryParams(JSON.parseArray(interfaceInfo.getQueryParams(), InvokeRequest.Field.class));
            interfaceInfoVo.setHeaderParams(JSON.parseArray(interfaceInfo.getHeaderParams(), InvokeRequest.Field.class));
            interfaceInfoVo.setBodyParams(JSON.parseArray(interfaceInfo.getBodyParams(), InvokeRequest.Field.class));
            return interfaceInfoVo;
        }).collect(Collectors.toList());
        return ResultUtils.success(interfaceInfoVoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @ApiOperation("分页获取列表")
    public BaseResponse<Page<InterfaceInfoVo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        Integer isShow = interfaceInfoQuery.getIsShow();
        Integer status = interfaceInfoQuery.getStatus();
        // content 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.eq("isShow", Objects.isNull(isShow) ? 1 : isShow);
        queryWrapper.eq("status", Objects.isNull(status) ? 1 : status);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        Page<InterfaceInfoVo> interfaceInfoVoPage = new Page<>();
        BeanUtils.copyProperties(interfaceInfoPage, interfaceInfoVoPage);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoPage.getRecords();
        List<InterfaceInfoVo> interfaceInfoVoList = interfaceInfoList.stream().map(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
            interfaceInfoVo.setQueryParams(JSON.parseArray(interfaceInfo.getQueryParams(), InvokeRequest.Field.class));
            interfaceInfoVo.setHeaderParams(JSON.parseArray(interfaceInfo.getHeaderParams(), InvokeRequest.Field.class));
            interfaceInfoVo.setBodyParams(JSON.parseArray(interfaceInfo.getBodyParams(), InvokeRequest.Field.class));
            return interfaceInfoVo;
        }).collect(Collectors.toList());
        interfaceInfoVoPage.setRecords(interfaceInfoVoList);
        return ResultUtils.success(interfaceInfoVoPage);
    }

    // endregion
    /**
     * 发布接口
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("接口上线(admin)")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        //1. 判断接口是否存在
        if(idRequest == null || idRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //2. 上线接口
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(id);
        interfaceInfo.setStatus(ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 下线接口
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")
    @ApiOperation("接口下线(admin)")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        //1. 判断接口是否存在
        if(idRequest == null || idRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if(oldInterfaceInfo == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //2. 下线接口
        oldInterfaceInfo.setStatus(OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(oldInterfaceInfo);
        return ResultUtils.success(result);
    }

//    /**
//     * 测试接口
//     *
//     * @param invokeRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/invoke")
//    @ApiOperation("调用第三方接口服务")
//    @Deprecated
//    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InvokeRequest invokeRequest,
//                                                      HttpServletRequest request) throws UnsupportedEncodingException {
//        //1. 判断接口是否存在
//        if(invokeRequest == null || invokeRequest.getId() <= 0){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        long id = invokeRequest.getId();
//        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
//        if(interfaceInfo == null){
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
//        }
//        if(interfaceInfo.getStatus() == OFFLINE.getValue()){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");
//        }
//        // 构建请求头参数
//        Map<String, Object> headerParams = getStringObjectMap(invokeRequest.getHeaderParams());
//        // 构建请求体参数（K-V形式）
//        //Map<String, Object> bodyParams = getStringObjectMap(invokeRequest.getBodyParams());
//
//        User loginUser = userService.getLoginUser(request);
//        String accessKey = loginUser.getAccessKey();
//        String secretKey = loginUser.getSecretKey();
//        // 使用用户的AK/SK
//        YuApiClient yuApiClient = new YuApiClient(accessKey,secretKey);
//        ApiService apiService = new ApiServiceImpl();
//        try {
//            CurrencyRequest currencyRequest = new CurrencyRequest();
//            currencyRequest.setMethod(interfaceInfo.getMethod());
//            currencyRequest.setPath(interfaceInfo.getUrl());
//            currencyRequest.setRequestParams(headerParams);
//            //currencyRequest.setBodyParams(bodyParams);
//            currencyRequest.setBodyJSON(invokeRequest.getJsonRequestBody());
//            ResultResponse response = apiService.request(yuApiClient, currencyRequest);
//            return ResultUtils.success(response.getData());
//        } catch (Exception e){
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
//        }
//    }

    /**
     *
     * @param invokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invokePlus")
    @ApiOperation("调用第三方接口服务（同步）")
    public BaseResponse<Object> invokeInterfaceInfoPlus(@RequestBody InvokeRequest invokeRequest,
                                                    HttpServletRequest request) {
        userService.getLoginUser(request);
        ResultResponse response = interfaceInfoService.invokeSync(invokeRequest, request);
        return ResultUtils.success(response.getData().get("data"));
    }

    /**
     *
     * @param invokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invokePlus/async")
    @ApiOperation("调用第三方接口服务（异步）")
    public BaseResponse<InterfaceInvokeInfo> invokeInterfaceInfoPlusAsync(@RequestBody InvokeRequest invokeRequest,
                                                        HttpServletRequest request) {
        userService.getLoginUser(request);
        InterfaceInvokeInfo interfaceInvokeInfo = interfaceInfoService.invokeAsync(invokeRequest,request);
        return ResultUtils.success(interfaceInvokeInfo);
    }
}
